package com.二叉树2;

import java.util.Deque;
import java.util.LinkedList;

public class TreeNode2 {
    public  TreeNode2 left;
    public TreeNode2 right;
    public  int val;

    public TreeNode2(int val,TreeNode2 left, TreeNode2 right) {
        this.left = left;
        this.right = right;
        this.val = val;
    }

    public TreeNode2(int value) {
        this.val = value;
    }
    public TreeNode2(int[] nums){
        this(nums[0]);
        TreeNode2 root = this;

        int curIndex = 1; //当前节点
        int nodeNumber = 2; //行长度
        Deque<TreeNode2> deque  = new LinkedList<>();
        deque.offer(root);
        TreeNode2 curNode ; //当前树
        int remainingLength =  nums.length - curIndex; //剩余长度
        while (remainingLength>=0){

            for(curIndex=curIndex;curIndex<curIndex+nodeNumber;curIndex+=2){
                curNode = deque.poll(); //取出头节点
                if(curIndex>=nums.length){
                    return;
                }
                curNode.left = new TreeNode2(nums[curIndex]);
                deque.offer(curNode.left);

                if(curIndex+1>=nums.length){
                    return;
                }
                curNode.right = new TreeNode2(nums[curIndex+1]);
                deque.offer(curNode.right);
            }
            curIndex += nodeNumber;
            remainingLength -= nodeNumber;
            nodeNumber = deque.size() * 2;

        }


    }
}
